--
-- Author: shunguo.chen
-- Date: 2017-11-16 14:30:56
--
-- BoxView  宝箱界面

local ShakeConfig = require("app.configs.ShakeConfig")
local Armature = app:getClass("Armature")
local BoxRender = import(".renders.BoxRender")

local fileName = string.getModeName(...)
local ClassRef = class(fileName, app.mvc.ViewBase)

ClassRef.VIEW_ROOT_RES = Res.BoxScene

local NEED_CNT_STR = L("NeedLuckKey")
local REST_CNT_STR = L("DailyLimit")
local TIP_STR_1 = L("lua_code_text_515")
local TIP_STR_2 = L("lua_code_text_425")
local SEASON_STR = L("ChampionshipSeasonLevel")
local RARE_TIPS1 = {"restrictedreward4_1_surface", "restrictedreward5_1_surface", "restrictedreward6_1_surface"}

local QualityColor = {
    cc.c3b(72, 255, 0),
    cc.c3b(0, 144, 255),
    cc.c3b(150, 0, 255),
    cc.c3b(255, 216, 1)
}

function ClassRef:show()
    self:setVisible(true)
    self:openAction()
    self:performWithDelay(function()
        self:playAction("animation", true)
    end, 1)
end

-- 关闭类型
-- -1 手动关闭
-- 0 非正常关闭
-- 1 打开宝箱
function ClassRef:getCloseType()
    return self._closeType
end

function ClassRef:ctor(viewType, data, boxSceneType)
    self._boxSceneType = boxSceneType
    if boxSceneType == Enums.BoxSceneType.luckBox then
        self.VIEW_ROOT_RES = Res.BoxScene
    elseif boxSceneType == Enums.BoxSceneType.pvpReward then
        self.VIEW_ROOT_RES = Res.PvpRewardScene
    else    -- default
        self.VIEW_ROOT_RES = Res.BoxScene
    end

    self.super.ctor(self, viewType, data)
end

-- data = {boxType=, id=}
function ClassRef:init()
    -- 下面三种宝箱需要钥匙
    -- dungeon = 1,    -- 地城宝箱
    -- pvp = 2,      -- 锦标赛宝箱
    -- eventBox = 3,   -- 世界事件活动宝箱

    self._closeType = 0

    local boxType = self._data.boxType
    local needKey = false
    local curCnt, resCnt
    --[[ if boxType == Enums.BoxType.dungeon or
        boxType == Enums.BoxType.pvp or
        boxType == Enums.BoxType.eventBox then

        needKey = true
        local maxCnt = GD:getSystemPar("charmdailymaxcostamount", 10)
        local _, todayCnt = UD.player:getCharmUsedInfo()
        curCnt = _
        resCnt = maxCnt - todayCnt
    else
        needKey = false
    end ]]

    local function onClick()
        if needKey then
            if curCnt < 1 then
                display.pushToast(TIP_STR_1)
            elseif resCnt < 1 then
                display.pushToast(TIP_STR_2)
            else
                self:_checkSelect()
            end
        else
            self:_checkSelect()
        end
    end


    if self._boxSceneType == Enums.BoxSceneType.luckBox then
        self._ui.tips_0:setVisible(needKey)
        self._ui.tips_1:setVisible(needKey)
        self._ui.tips_2:setVisible(needKey)
        self._ui.tips_img_2:setVisible(needKey)
        self._ui.bg3:setVisible(needKey)
        self._ui.icon:setVisible(needKey)
        --[[ if needKey then
            self._ui.tips_1:setString(string.format(NEED_CNT_STR, 1, curCnt))
            self._ui.tips_2:setString(string.format(REST_CNT_STR, resCnt))
        end ]]
        if boxType == Enums.BoxType.dungeon or boxType == Enums.BoxType.pvp or boxType == Enums.BoxType.eventBox then
            self._ui.tips_0:setVisible(true)
            self._ui.tips_1:setVisible(true)
            self._ui.tips_2:setVisible(true)
            self._ui.tips_img_2:setVisible(true)

            self._ui.tips_0:setString(L(RARE_TIPS1[boxType]))
            local maxNum1 = UD:getLuckBoxDailyMaxNum(boxType)
	        local num1 = UD:getLuckBoxRestTimesByType(boxType)
            self._ui.tips_1:setString(string.format( L("dailyLuckboxdaily"), num1, maxNum1 ))
            local maxNum2 = UD:getLuckBoxWeeklyMaxNum(boxType)
            local num2 = UD:getLuckBoxWeeklyRestTimesByType(boxType)
            self._ui.tips_2:setString(string.format( L("dailyLuckboxweekly"), num2, maxNum2 ))
        end

        self._ui.Button_close:setVisible(false)
        self._ui.tips_3:setVisible(false)

        self._ui.Button_quxiao:addClickEventListener(function()
            self._closeType = -1
            self:closeView()
        end)
        self._ui.Button_queding:addClickEventListener(onClick)

        self:_handleUiVisible()
    elseif self._boxSceneType == Enums.BoxSceneType.pvpReward then
        self._ui.Button_quxiao:addClickEventListener(function()
            self._closeType = -1
            self:closeView()
        end)
        self._ui.Button_queding_1:addClickEventListener(onClick)
        self._ui.Button_queding:addClickEventListener(onClick)
        self._ui.tips_up:setVisible(false)
        self._ui.tips_down:setVisible(false)
        self._ui.tips_2:setVisible(false)
        self:_handleUiVisibleEx()
    end

    -- 宝箱icon   
    local icon = self._ui["Panel/icon_1/icon"]
    if self._data.boxType ~= Enums.BoxType.guildChallenge then
        local path = Res.BoxIconAry[self._data.boxType]
        if self._data.boxType == Enums.BoxType.associate then
            -- 读道具表找icon(目前已知是世界boss宝箱)
            local config = GD:queryItemById(self._data.itemId)
            if config then
                path = "art/item_icon/"..config.icon..".png"
            end
        end
        -- 冠军赛
        if self._data.boxType == Enums.BoxType.champion then
            if self._data.championType == 0 then
                path = "art/treasure/treasure_4.png"
            end
        end
        if path then
            icon:loadTexture(path)
        end
    end

    self._icon = icon
    display.uiAddClick(icon, onClick)
    local size = icon:getContentSize()
    self._iconPos = icon:convertToWorldSpace(cc.p(size.width/2, size.height/2))
end

-- 根据类型处理UI可见性
function ClassRef:_handleUiVisible()
    local titleStr
    if self._data.boxType == Enums.BoxType.dungeon then
        titleStr = L("restrictedreward4")
    elseif self._data.boxType == Enums.BoxType.secret then
        titleStr = L("lua_code_text_392")
    elseif self._data.boxType == Enums.BoxType.pvp then
        titleStr = L("restrictedreward5")
    elseif self._data.boxType == Enums.BoxType.eventBox then -- 世界活动副本宝箱
        titleStr = L("restrictedreward6")
    elseif self._data.boxType == Enums.BoxType.guildChallenge then -- 公会挑战
        titleStr = L("GuildBox")
        self._ui.tips_3:setVisible( true )
        local challengInfo = GD:queryGuildChallengeById( self._data.guildChallengeID )
        if challengInfo then
            self._ui.tips:setString(string.format(L("GuildChallengeComplete"),L(challengInfo.name)))
            self._ui["Panel/icon_1/icon"]:loadTexture(string.format("%s%s%d.png",Res.guildIconPath,"ghchest_",tonumber(challengInfo.quality)))
        end

        self._ui.tips_3:findChild("text"):setString(L("SuperNotice_UseLuckBox"))
    elseif self._data.boxType == Enums.BoxType.champion then -- 冠军赛挑战
        titleStr = L("lua_code_text_92")
    end

    titleStr = titleStr or L("lua_code_text_326")

    self._ui.tlt:setString( titleStr )
end

function ClassRef:_handleUiVisibleEx()
    if self._data.boxType == Enums.BoxType.guildChallenge then
        local challengInfo = GD:queryGuildChallengeById( self._data.guildChallengeID )
        if challengInfo then
            self._ui.tips:setString(string.format(L("GuildChallengeComplete"),L(challengInfo.name)))
            self._ui["Panel/icon_1/icon"]:loadTexture(string.format("%s%s%d.png",Res.guildIconPath,"ghchest_",tonumber(challengInfo.quality)))
        end

        self._ui.tlt:setString( L("GuildBox") )
        self._ui.tips_2:setVisible(true)
    elseif self._data.boxType == Enums.BoxType.championSeason then
        self._ui.tlt:setString( L("ChampionshipSeasonBox") )
        self._ui.tips:setString(string.format(SEASON_STR, self._data.seasonLv))
        self._ui.tips_2:setVisible(true)
    elseif self._data.boxType == Enums.BoxType.challengeSeason then
        self._ui.tlt:setString(L("challengeTips17"))
        self._ui.tips:setString(string.format(L("challengeTips18"), self._data.seasonLv))
        self._ui.tips_2:setVisible(true)
    elseif self._data.boxType == Enums.BoxType.eliteArenaSeason then -- 精英竞技场
        self._ui.tlt:setString(L("EliteMatchTip15"))
        self._ui.tips:setString(string.format(L("EliteMatchTip17"), self._data.seasonLv))
        self._ui.tips_2:setVisible(true)
    elseif self._data.boxType == Enums.BoxType.eliteDuelSeason then -- 精英决斗赛
        self._ui.tlt:setString(L("EliteMatchTip16"))
        self._ui.tips:setString(string.format(L("EliteMatchTip17"), self._data.seasonLv))
        self._ui.tips_2:setVisible(true)
    elseif self._data.boxType == Enums.BoxType.associate then -- 使用关联道具
        self._ui.tips:setString(L("boxOpenDes"))
        self._ui.tips_up:setVisible(true)
        self._ui.tips_down:setVisible(true)
        self._ui.tips_up:setString(self._data.strs[1])
        self._ui.tips_down:setString(self._data.strs[2])
        self._ui.tlt:setString(self._data.name)

        -- 显示取消按钮
        self._ui.Button_quxiao:setVisible(true)
        self._ui.Button_queding_1:setVisible(true)
        self._ui.Button_queding:setVisible(false)
    end

    -- 设置标题居中
    display.setNodesMiddle(self._ui.Panel, self._ui.tips_img, self._ui.tips)
end

function ClassRef:_checkSelect()
    display.setBtnTouchEnable(self._ui.Button_queding, false)
    display.setBtnTouchEnable(self._ui.Button_quxiao, false)
    -- 点击后设置取消按钮2s不可点，防止断网卡死和点击开启按钮后又迅速点击取消按钮造成的表现bug
    scheduler.newCron(function()
        if self and self._ui and cc.isAlive(self._ui.Button_quxiao) then
            display.setBtnTouchEnable(self._ui.Button_quxiao, true)
        end
    end, 2)
    if self._ui.Button_queding_1 then
        display.setBtnTouchEnable(self._ui.Button_queding_1, false)
    end

    self._icon:setTouchEnabled(false)

    local data = self._data
    executeFunc(self._onOperate, "openBox", data)
    -- if data.boxType == Enums.BoxType.dungeon then -- 地城宝箱没有选择，直接定位dunJewel
    --     -- 没有类型，需要选择
    --     --if data.type then
    --         executeFunc(self._onOperate, "openBox", data)
    --     --else
    --         --self:_addChoosePanel()
    --     --end
    -- elseif data.boxType == Enums.BoxType.secret then
    --     executeFunc(self._onOperate, "openBox", data)
    -- elseif data.boxType == Enums.BoxType.pvp then
    --     -- 竞技场宝箱直接打开
    --     executeFunc(self._onOperate, "openBox", data)
    -- elseif data.boxType == Enums.BoxType.eventBox then -- 世界活动副本宝箱
    --     executeFunc(self._onOperate, "openBox", data)
    -- elseif data.boxType == Enums.BoxType.guildChallenge then -- 公会挑战
    --     executeFunc(self._onOperate, "openBox", data)
    -- elseif data.boxType == Enums.BoxType.champion then -- 冠军赛挑战
    --     executeFunc(self._onOperate, "openBox", data)
    -- elseif data.boxType == Enums.BoxType.championSeason then    -- 锦标赛赛季宝箱
    --     executeFunc(self._onOperate, "openBox", data)
    -- elseif data.boxType == Enums.BoxType.challengeSeason then    -- 锦标赛赛季宝箱
    --     executeFunc(self._onOperate, "openBox", data)
    -- elseif data.boxType == Enums.BoxType.associate then -- 使用关联道具
    --     executeFunc(self._onOperate, "openBox", data)
    -- end
end

function ClassRef:_addChoosePanel()
    local choosePanel = cc.CSLoader:createNode(Res.BoxChooseScene, true)
    choosePanel:setContentSize(display.width, display.height)
    choosePanel:setAnchorPoint(0.5, 0.5)
    choosePanel:setPosition(display.width/2, display.height/2)
    display.setAutoScale(choosePanel)
    ccui.Helper:doLayout(choosePanel)
    self:addChild(choosePanel, 2)
    self._choosePanel = choosePanel

    local panel = choosePanel:getChildByName("Panel")
    display.uiAddClick(panel:findChild("Panel_left"), function()
        self._data.type = "equip"
        executeFunc(self._onOperate, "openBox", self._data)
        self:_removeChoosePanel()
    end, true, 0.02)

    display.uiAddClick(panel:findChild("Panel_right"), function()
        self._data.type = "jewel"
        executeFunc(self._onOperate, "openBox", self._data)
        self:_removeChoosePanel()
    end, true, 0.02)
end

function ClassRef:_removeChoosePanel()
    if self._choosePanel then
        self._choosePanel:removeFromParent()
        self._choosePanel = nil
    end
end

function ClassRef:openBox(items)
    -- print("openBox", index)
    AM.playSoundById(2392)

    self._closeType = 1
    self._items = items

    local scene = cc.Director:getInstance():getRunningScene()
    --震屏
    local conf = ShakeConfig:getConfig(12)
    display.nodeShake(self, conf)

    self:performWithDelay(function()
        local params = {
            armatureName = "kbx_qp",
            path = "armatures/effect/kbx_qp"
        }
        local armature = Armature.create(params)
        armature:setPosition(self._iconPos)
        self:addChild(armature, 2)

        local ani = {
            name = "kbx_qp",
            playTimes = 1,
            completeCallback = function(sender)
                sender:removeFromParent()
            end
        }
        armature:playAni(ani)
        armature:onFrameEvent(function(sender, name)
            if name == "hjm" then
                self:_showOpenPanel()
            end
        end)
    end, conf.duration*2/3)
end

function ClassRef:_showOpenPanel()
    local bg = ccui.ImageView:create(Res.BoxBg)
    bg:ignoreContentAdaptWithSize(false)
    bg:setContentSize(display.size)
    bg:setPosition(display.cx, display.cy)
    self:addChild(bg)
    self._root:removeFromParent()
    self._hasCloseAct = false
    self._timeline = nil

    -- 是否全部打开，全部打开只震屏一次（最强的）
    self._isOpenAll = false

    self._root, self._uiBinding = cc.CSLoader:createNode(Res.BoxOpenScene, true, true, true)
    self._root:setContentSize(display.width, display.height)
    self._root:setAnchorPoint(0.5, 0.5)
    self._root:setPosition(display.width/2, display.height/2)
    display.setAutoScale(self._root)
    ccui.Helper:doLayout(self._root)

    self._root:setName(self:getViewName())
    self._ui = display.uiDelegate(self._root)
    self:addChild(self._root, 1)

    self._ui.Button:addClickEventListener(function()
            self:_openAllBox()
        end)

    -- 未打开的宝箱
    self._boxs = {0,0,0,0,0}
    for i,v in ipairs(self._boxs) do
        local panel = self._ui["Panel_" .. i]
        display.uiAddClick(panel, function()
                self:_openBox(i)
            end)
        self._boxs[i] = panel
        self:_createBoxArmature(i)
    end

    -- 已打开的宝箱
    self._openBoxs = {0,0,0,0,0}
    for i,v in ipairs(self._openBoxs) do
        local render = BoxRender.create(nil, self._ui["Panel_open_" .. i])
        render:setLocalZOrder(2)
        render:setData(self._items[i])
        self._openBoxs[i] = render
    end

    -- box是否打开
    self._boxStatus = {0,0,0,0,0}
end

function ClassRef:_createBoxArmature(index)
    local panel = self._boxs[index]
    local size = panel:getContentSize()
    local quality = self._items[index].quality

    local params = {
        armatureName = "kbx_xhg",
        path = "armatures/effect/kbx_xhg"
    }
    local armature = Armature.create(params)
    armature:setPosition(size.width/2, size.height/2)
    panel:addChild(armature, -1)
    armature:gotoAndPlay("kbx_xhg", math.random())

    if quality > 1 then
        armature:setColor(QualityColor[quality-1])
    end
end

function ClassRef:_openAllBox()
    self._isOpenAll = true

    local quality = 1
    for i,v in ipairs(self._boxStatus) do
        if v == 0 then
            if self._items[i].quality > quality then
                quality = self._items[i].quality
            end
            self:_openBox(i)
        end
    end

    -- print("_openAllBox quality", quality)

    local conf
    if quality == 5 then
        conf = ShakeConfig:getConfig(11)
    elseif quality == 4 then
        conf = ShakeConfig:getConfig(2)
    else
        conf = ShakeConfig:getConfig(1)
    end
    display.nodeShake(self, conf)
end

function ClassRef:_openBox(index)
    -- print("_openBox", index)

    self._boxStatus[index] = 1

    -- 检查是否是最后一个，需要隐藏按钮
    local openNum = 0
    for i,v in ipairs(self._boxStatus) do
        openNum = openNum + v
    end
    local isLastOne = openNum == #self._boxStatus
    if isLastOne then
        self._ui.Button:setVisible(false)
    end

    self:_createOpenArmature(index, isLastOne)
end

function ClassRef:_createOpenArmature(index, isLastOne)
    -- print("_createOpenArmature", index, isLastOne)

    isLastOne = isLastOne or false
    local panel = self._ui.Panel
    local posX = self._boxs[index]:getPositionX()
    local posY = self._boxs[index]:getPositionY()
    local quality = self._items[index].quality

    self._boxs[index]:setVisible(false)

    -- 底板特效
    local params = {
        armatureName = "kbx_zkdh",
        path = "armatures/effect/kbx_zkdh"
    }
    local armBg = Armature.create(params)
    armBg:setPosition(posX, posY)
    panel:addChild(armBg, 1)
    local ani = {
        name = "kbx_zkdh",
        playTimes = 1,
        completeCallback = function(sender)
            local action = cc.FadeIn:create(5/24)
            local box = self._openBoxs[index]
            box:setVisible(true)
            box:setOpacity(0)
            box:runAction(action)
        end
    }
    armBg:playAni(ani)

    -- 根据品质替换不同底板
    if quality > 1 then
        local fileName = "kbx_bg" .. quality
        local params = {
            armatureName = "dh/bg1",
            path = "armatures/effect/" .. fileName
        }
        local arm1 = Armature.create(params)
        armBg:setSlotArmature("xbnxdf", arm1)

        local params = {
            armatureName = "dh/bg2",
            path = "armatures/effect/" .. fileName
        }
        local arm2 = Armature.create(params)
        armBg:setSlotArmature("xbzsd", arm2)
    end

    -- 上层特效
    local params = {
        armatureName = "kbx_zktx",
        path = "armatures/effect/kbx_zktx"
    }
    local armFg = Armature.create(params)
    armFg:setPosition(posX, posY)
    panel:addChild(armFg, 3)
    local ani = {
        name = "kbx_zktx",
        playTimes = 1,
        completeCallback = function(sender)
            sender:removeFromParent()
            if isLastOne then
                self:_openBoxOver()
            end
        end
    }
    armFg:playAni(ani)

    if quality > 1 then
        armFg:setColor(QualityColor[quality-1])
    end

    -- 震屏
    if not self._isOpenAll then
        local conf
        if quality == 5 then
            conf = ShakeConfig:getConfig(11)
        elseif quality == 4 then
            conf = ShakeConfig:getConfig(2)
        else
            conf = ShakeConfig:getConfig(1)
        end
        display.nodeShake(self, conf)
    end
end

function ClassRef:_openBoxOver()
    -- print("_openBoxOver")
    self._ui.tips:setVisible(true)
    self._root:getTimeline():gotoFrameAndPlay(0, true)

    display.uiAddClick(self._ui.Panel, function()
        self:closeView()
    end)
end

return ClassRef
